//
//  LWResumeViewController.m
//  IOSResume
//
//  Created by wynn on 16/4/20.
//  Copyright © 2016年 wynn. All rights reserved.
//

#import "LWResumeViewController.h"
#import "ResumeInfo.h"
#import "LWEditingResumeViewController.h"
#import "FSMediaPicker.h"

@interface LWResumeViewController()<UIImagePickerControllerDelegate,UINavigationControllerDelegate,FSMediaPickerDelegate>
{
    CGFloat _cellHeight[2];
    CGFloat scrollViewContentSizeHeight;
    CGFloat fontPadding;
    UIFont *tagFontSize;
    UIFont *labelFontSize;
}
@property (nonatomic, strong) NSMutableArray *cellData;
@property (nonatomic, strong) NSMutableArray *cellArray;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) UIButton *saveButton;
@property (nonatomic, strong) UIButton *backButton;
@property (nonatomic, strong) UIImageView *backGroundImageView;
@property (nonatomic, strong) ResumeInfo *resumeInfo;
@property (nonatomic, strong) UIScrollView *scrollView;
@property (nonatomic, strong) BmobUser *user;
@property (nonatomic, strong) FSMediaPicker *picker;
@end

@implementation LWResumeViewController

- (NSMutableArray *)cellData
{
    if (!_cellData) {
        NSMutableArray *tempArray = [NSMutableArray arrayWithArray:@[@"姓名", @"性别", @"民族", @"年龄", @"现居住地", @"学历／专业", @"项目经历", @"工作经历"]];
        _cellData = tempArray;
    }
    return _cellData;
}

- (NSMutableArray *)cellArray
{
    if (!_cellArray) {
        _cellArray = [NSMutableArray array];
    }
    return _cellArray;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    // 设置背景图片
    if (!_backGroundImageView) {
        UIImage *backGroundImage = [UIImage imageNamed:@"defaultBackground"];
        self.backGroundImageView = [[UIImageView alloc] initWithImage:backGroundImage];
        self.backGroundImageView.frame = self.view.bounds;
        [self.view addSubview:self.backGroundImageView];
        
        self.avatar = [[UIImageView alloc] init];
        self.avatar.frame = CGRectMake((SCREEN.width - 100)*0.5, 25, 100, 100);
        self.avatar.layer.cornerRadius = 50.0f;
        self.avatar.layer.masksToBounds = YES;
        self.avatar.hidden = YES;
        [self.view addSubview:_avatar];
        
        [self.avatar setUserInteractionEnabled:YES];
        [self.avatar addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(pickImageClick:)]];
        
        [self initBackButton];
        [self initSaveButton];
        
        [self loadOnlineDataWithUser];
    }
}

- (void)viewWillAppear:(BOOL)animated
{
    [self initResumeView];
}
#pragma mark - 初始化返回和保存按钮
- (void)initBackButton
{
    if (!_backButton) {
        _backButton = [UIButton buttonWithType:UIButtonTypeCustom];
        _backButton.frame = CGRectMake(startMargin, startMargin, startMargin, startMargin);
        [_backButton setTitle:@"返回" forState:UIControlStateNormal];
        [_backButton setTitleColor:MILK_WHITE forState:UIControlStateNormal];
        [_backButton setTitleColor:MILK_GRAY forState:UIControlStateHighlighted];
        [_backButton setBackgroundColor:MILK_RED];
        [_backButton addTarget:self action:@selector(backClicked) forControlEvents:UIControlEventTouchUpInside];
    }
    
    [self.view addSubview:_backButton];
}

- (void)initSaveButton
{
    if (!_saveButton) {
        _saveButton = [UIButton buttonWithType:UIButtonTypeCustom];
        _saveButton.frame = CGRectMake(SCREEN.width - startMargin - startMargin, startMargin, startMargin, startMargin);
        [_saveButton setTitle:@"保存" forState:UIControlStateNormal];
        [_saveButton setTitleColor:MILK_WHITE forState:UIControlStateNormal];
        [_saveButton setTitleColor:MILK_GRAY forState:UIControlStateHighlighted];
        [_saveButton setBackgroundColor:MILK_RED];
        [_saveButton addTarget:self action:@selector(saveClick) forControlEvents:UIControlEventTouchUpInside];
    }
    
    [self.view addSubview:_saveButton];
}
#pragma mark - 刷新显示简历的view
//@[_name, _sex, _nation, _age, _location, _education, _projects, _jops]
- (void)initResumeView
{
    if (!_scrollView){
        _scrollView = [[UIScrollView alloc] init];
        _scrollView.frame = CGRectMake(0, self.avatar.frame.origin.y+self.avatar.bounds.size.height, SCREEN.width, SCREEN.height-self.avatar.frame.origin.y-self.avatar.bounds.size.height);
        [self.view addSubview:_scrollView];
        scrollViewContentSizeHeight = 0.0f;
        fontPadding = 16.0f;
        tagFontSize = [UIFont systemFontOfSize:24];
        labelFontSize = [UIFont systemFontOfSize:28];
    }else {
        for (UIView *view in self.scrollView.subviews) {
            if ([view isKindOfClass:[UILabel class] ]) {
                [view removeFromSuperview];
            }
        }
        scrollViewContentSizeHeight = 0.0f;
    }
    
    for (int i=0; i<self.cellData.count; i++) {
        UILabel *nameTag = [[UILabel alloc] initWithFrame:CGRectZero];
        nameTag.text = self.cellData[i];
        nameTag.textColor = [UIColor whiteColor];
        [nameTag setFont:tagFontSize];
        [nameTag setNumberOfLines:0];
        CGSize nameTagSize = [self sizeWithString:self.cellData[i] font:tagFontSize];
        nameTag.frame = CGRectMake(fontPadding, scrollViewContentSizeHeight, SCREEN.width-fontPadding, nameTagSize.height+fontPadding);
        scrollViewContentSizeHeight +=nameTagSize.height+fontPadding;
        [self.scrollView addSubview:nameTag];
        
        if (i<self.resumeInfo.resumeInfoArray.count&&self.resumeInfo.resumeInfoArray[i]) {
            UILabel *nameLabel = [[UILabel alloc] initWithFrame:CGRectZero];
            nameLabel.tag = i;
            nameLabel.text = self.resumeInfo.resumeInfoArray[i];
            nameLabel.textColor = [UIColor whiteColor];
            [nameLabel setFont:labelFontSize];
            [nameLabel setNumberOfLines:0];
            CGSize nameLabelSize = [self sizeWithString:self.resumeInfo.resumeInfoArray[i] font:labelFontSize];
            nameLabel.frame = CGRectMake(fontPadding, scrollViewContentSizeHeight, SCREEN.width-fontPadding, nameLabelSize.height+fontPadding);
            scrollViewContentSizeHeight +=nameLabelSize.height+fontPadding;
            [self.scrollView addSubview:nameLabel];
            
            if (self.showUserResume)
            {
                [nameLabel setUserInteractionEnabled:YES];
                [nameLabel addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(labelClick:)]];
            }
        }
    }
    
    CGSize contentSize = CGSizeMake(SCREEN.width, scrollViewContentSizeHeight);
    self.scrollView.contentSize = contentSize;
}
#pragma mark - IBAction
- (void)backClicked
{
    if (self.delegate && [self.delegate respondsToSelector:@selector(resumeViewControllerDidClickedDismissButton:)]) {
        [self.delegate resumeViewControllerDidClickedDismissButton:self];
    }
}

- (void)saveClick
{
    if (self.showUserResume) {
        BmobObject  *resumeObj = [BmobObject objectWithClassName:@"Resume"];
        self.resumeInfo = [ResumeInfo shareModel];
        for (int i=0; i<self.cellData.count; i++) {
            [resumeObj setObject:self.resumeInfo.resumeInfoArray[i] forKey:self.cellData[i]];
        }
        [resumeObj setObject:self.queryEmail forKey:@"username"];
        [resumeObj saveInBackgroundWithResultBlock:^(BOOL isSuccessful, NSError *error) {
            if (isSuccessful) {
                [SVProgressHUD showSuccessWithStatus:@"提交成功"];
            }else {
                [SVProgressHUD showErrorWithStatus:@"提交失败"];
            }
        }];
    }
}

- (void)labelClick:(UITapGestureRecognizer *)gestureRecognizer
{
    UILabel *label = (UILabel *)[gestureRecognizer view];
    NSInteger indexClick = label.tag;
    NSString *str = label.text;
    LWEditingResumeViewController *editingResumeVC = [[LWEditingResumeViewController alloc] init];
    editingResumeVC.index = indexClick;
    editingResumeVC.oldText = str;
//    [self.navigationController pushViewController:editingResumeVC animated:YES];
    [self presentViewController:editingResumeVC animated:YES completion:nil];
}

- (void)pickImageClick:(UITapGestureRecognizer *)gestureRecognizer
{
    
    if (!_picker) {
        self.picker = [[FSMediaPicker alloc] init];
        self.picker.delegate = self;
        self.picker.mediaType = FSMediaTypePhoto;
        self.picker.editMode = FSEditModeCircular;
    }
    
    [self.picker showFromView: [gestureRecognizer view]];
}
#pragma mark - 根据字符串计算label的高度
-(CGSize)sizeWithString:(NSString *)string font:(UIFont *)font

{
    CGRect rect = [string boundingRectWithSize:CGSizeMake(SCREEN.width, 8000)//限制最大的宽度和高度
                                       options:NSStringDrawingTruncatesLastVisibleLine | NSStringDrawingUsesFontLeading  |NSStringDrawingUsesLineFragmentOrigin//采用换行模式
                                    attributes:@{NSFontAttributeName: font}//传人的字体字典
                                       context:nil];
    
    return rect.size;
}
#pragma mark - 从服务器上查询简历信息
- (void)loadOnlineDataWithUser{
    self.resumeInfo = [ResumeInfo shareModel];
    if (!_user) {
        self.user = [BmobUser getCurrentUser];
    }
    BmobQuery *bquery = [BmobQuery queryWithClassName:@"Resume"];
    if (self.showUserResume) {
        [bquery whereKey:@"username" equalTo:self.user.username];
    }else {
        [bquery whereKey:@"username" equalTo:self.queryEmail];
    }
    [bquery findObjectsInBackgroundWithBlock:^(NSArray *array, NSError *error) {
        if (error){
            //进行错误处理
        }else{
            for (BmobObject *obj in array) {
                //@[_name, _sex, _nation, _age, _location, _education, _projects, _jops]
                NSString *name = [obj objectForKey:@"name"];
                if (name) {
                    [self.resumeInfo.resumeInfoArray replaceObjectAtIndex:0 withObject:name];
                }

                NSString *sex = [obj objectForKey:@"sex"];
                if (sex) {
                    [self.resumeInfo.resumeInfoArray replaceObjectAtIndex:1 withObject:sex];
                }
                
                NSString *nation = [obj objectForKey:@"nation"];
                if (nation) {
                    [self.resumeInfo.resumeInfoArray replaceObjectAtIndex:2 withObject:nation];
                }
                
                NSString *age = [obj objectForKey:@"age"];
                if (age) {
                    [self.resumeInfo.resumeInfoArray replaceObjectAtIndex:3 withObject:age];
                }
                
                NSString *location = [obj objectForKey:@"location"];
                if (location) {
                    [self.resumeInfo.resumeInfoArray replaceObjectAtIndex:4 withObject:location];
                }
                
                NSString *education = [obj objectForKey:@"education"];
                if (education) {
                    [self.resumeInfo.resumeInfoArray replaceObjectAtIndex:5 withObject:education];
                }

                NSString *projects = [obj objectForKey:@"projects"];
                if (projects) {
                    [self.resumeInfo.resumeInfoArray replaceObjectAtIndex:6 withObject:projects];
                }
            
                NSString *jobs = [obj objectForKey:@"jobs"];
                if (jobs) {
                    [self.resumeInfo.resumeInfoArray replaceObjectAtIndex:7 withObject:jobs];
                }
                
            }
            [self initResumeView];
        }
    }];
    
}

#pragma mark - 上传头像到Bmob服务器
- (void)uploadImageToBmobWithImageName:(NSString *)imageName
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
    NSString *filePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:[NSString stringWithFormat:@"pic_%@.png", imageName]];   // 保存文件的名称

    BmobObject *obj = [[BmobObject alloc] initWithClassName:@"Photo"];

    [self objSaveFileInBack:obj withFilePath:filePath andImageName:imageName];
}

- (void)objSaveFileInBack:(BmobObject *)obj withFilePath:(NSString *)filePath andImageName:(NSString *)imageName
{
    BmobFile *file1 = [[BmobFile alloc] initWithFilePath:filePath];
    [file1 saveInBackground:^(BOOL isSuccessful, NSError *error) {
        //如果文件保存成功，则把文件添加到filetype列
        if (isSuccessful) {
            [obj setObject:file1  forKey:@"filetype"];
            [obj setObject:[NSString stringWithFormat:@"pic_%@.png", imageName] forKey:@"filename"];
            [obj saveInBackground];
        }else{
            //进行处理
        }
    }];
}
#pragma mark - 将图片保存到应用沙盒
- (BOOL)saveImageToSandbox:(UIImage *)image whithImageName:(NSString *)imageNmae
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
    NSString *filePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:[NSString stringWithFormat:@"pic_%@.png", imageNmae]];   // 保存文件的名称
    return [UIImagePNGRepresentation([self scaleToSize:image size:CGSizeMake(100, 100)])writeToFile: filePath atomically:YES];
}
#pragma mark - 将图片缩小到100x100
- (UIImage *)scaleToSize:(UIImage *)img size:(CGSize)size{
    // 创建一个bitmap的context
    // 并把它设置成为当前正在使用的context
    UIGraphicsBeginImageContext(size);
    // 绘制改变大小的图片
    [img drawInRect:CGRectMake(0,0, size.width, size.height)];
    // 从当前context中创建一个改变大小后的图片
    UIImage* scaledImage =UIGraphicsGetImageFromCurrentImageContext();
    // 使当前的context出堆栈
    UIGraphicsEndImageContext();
    //返回新的改变大小后的图片
    return scaledImage;
}

#pragma mark - 相册选择器
- (void)mediaPicker:(FSMediaPicker *)mediaPicker didFinishWithMediaInfo:(NSDictionary *)mediaInfo
{
    //    self.imageView.image = mediaInfo.editedImage; // Or mediaInfo[UIImagePickerControllerEditedImage]
    self.avatar.image = mediaInfo.editedImage;
    BOOL saveResult = [self saveImageToSandbox:mediaInfo.editedImage whithImageName:self.user.objectId];
    if (saveResult) {
        [self uploadImageToBmobWithImageName:self.user.objectId];
    }
}


@end

